<?php

/**
 * Subclass for representing a row from the 'product' table.
 *
 * 
 *
 * @package lib.model
 */ 
class Product extends BaseProduct
{

    const PROMO_TAG             = 1;
    const NEW_TAG               = 2;

    
    public static function getTagsList()
    {
        return array(
            Product::PROMO_TAG => 'product_promo_tag'
            , Product::NEW_TAG => 'product_new_tag'
        );
    }
    
public static function getSearchProduct($search)
    {
        /* @var $obj Product */
    
        $query = 
            'SELECT
                    product.category_id
                    , product.user_id
                    , product.code
                    , product.price
                    , product.price_promo
                    , product_i18n.id
                    , product_i18n.name
                    , product_i18n.text
                    , product_i18n.summary
                    , product_i18n.text_promo
                    , files.uname
            FROM product_i18n LEFT JOIN files
                 ON product_i18n.id = files.obj_id
                    and files.obj_type = 5
                inner join product 
                    on product_i18n.id = product.id
            WHERE product_i18n.name like "%' . $search . '%"  
            ORDER BY product_i18n.name
            ';
        
        $stmt = Propel::getConnection()->prepareStatement($query);
        $rs = $stmt->executeQuery();

        $arSearchProduct = array();


        // Search for first image
        while( $rs->next() )
        {
            $obj = new Product();
        
            $obj->setId($rs->getInt('id'));
            $obj->setCategoryId($rs->getInt('category_id'));
            //$obj->setObjType($rs->getInt('obj_type'));
            $obj->setUserId($rs->getInt('user_id'));
            //$obj->setAction($rs->getInt('action'));
            //$obj->setStatusId($rs->getInt('status_id'));
            $obj->setName($rs->get('name'));
            $obj->setText($rs->get('text'));
            $obj->setCode($rs->get('code'));
            $obj->setPrice($rs->get('price'));
            $obj->setPricePromo($rs->get('price_promo'));

            $arSearchProduct[] = $obj;
        }  // END WHILE ( list results )

        //debugvar($arObjects, 'arObjects');
        return $arSearchProduct;
    }
    
public static function getSearchCategory($search)
    {
        $query = 
            'SELECT category.user_id
                    , category.branch
                    , category_i18n.id
                    , category_i18n.name
                    , category_i18n.text
                    , files.uname
            FROM category_i18n LEFT JOIN files ON category_i18n.id = files.obj_id
                    and files.obj_type = 6
                        inner join category
                    on category_i18n.id = category.id
            WHERE category_i18n.name like "%' . $search . '%" 
                    and category.status_id = "' . MyConstants::OBJ_STATUS_ACTIVE . '"   
            ORDER BY category_i18n.name
            ';

        $stmt = Propel::getConnection()->prepareStatement($query);
        $rs = $stmt->executeQuery();

        $arSearchCategory = array();


        // Search for first image
        while( $rs->next() )
        {
            $obj = new Category();
        
            $obj->setId($rs->getInt('id'));
            //$obj->setObjType($rs->getInt('obj_type'));
            $obj->setUserId($rs->getInt('user_id'));
             $obj->setBranch($rs->getInt('branch'));
            //$obj->setAction($rs->getInt('action'));
            //$obj->setStatusId($rs->getInt('status_id'));
            //$obj->setUname($rs->get('uname'));
            $obj->setName($rs->get('name'));
            $obj->setText($rs->get('text'));

            $arSearchCategory[] = $obj;
        }  // END WHILE ( list results )

        //debugvar($arObjects, 'arObjects');
        return $arSearchCategory;
    }
    
    public function getPriceByCurrencyCode($currencyCode = 'LTL')
    {
    	$arConverter = MyConstants::getCurrencyConverter();
        $currency = $this->getCurrencyCode();
        $toCurrency = $currencyCode;
        $factorKey = $currency . '_' . $toCurrency;
        $price = $this->getPrice();
        if( !empty($arConverter[$factorKey]) && ($arConverter[$factorKey] != $currency) )
        {
        	$price = $this->getPrice() * $arConverter[$factorKey];
        }
        return $price/100;
    }
	public function getPromoPriceByCurrencyCode($currencyCode = 'LTL')
    {
        $arConverter = MyConstants::getCurrencyConverter();
        $currency = $this->getCurrencyCode();
        $toCurrency = $currencyCode;
        $factorKey = $currency . '_' . $toCurrency;
        $price = $this->getPromoPriceFmt();
        if( !empty($arConverter[$factorKey]) && ($arConverter[$factorKey] != $currency) )
        {
            $price = $this->getPromoPriceFmt() * $arConverter[$factorKey];
        }
        return $price;
    }
    
    public static function getTagName($tagId)
    {
        switch($tagId)
        {
            case Product::PROMO_TAG:
                return 'product_promo_tag';
            case Product::NEW_TAG:
                return 'product_new_tag';
        }
        
        return sprintf('??%s??', $tagId);
    }
    
    public static function generateCode()
    {
        $arDigits = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
        // Letter 'O' is not in list, because it is difficult to separate from digit 0
        $arAlpha = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');

        $strUid = '';

        $totalSymbols = sfConfig::get('app_limits_length_of_code', 8);
        $totalAlphas = sfConfig::get('app_limits_alphas_in_code', $totalSymbols);
        $mask = sfConfig::get('app_limits_mask_of_code', '%s');
        
        if( !strstr($mask, '%s') )
        {
            throw new Exception('Mask for product code is invalid [' . $mask . '], should contain %s!');
        }
        
        // Format unique code
        for( $i = 0; $i < $totalSymbols; $i++ )
        {
            // First will be alpha
            if( $i < $totalAlphas )
            {
                // 25 letters, cause 'O' is dropped
                $pos = mt_rand(0, 24);
                $strUid .= $arAlpha[$pos];
            }else
            {
                $pos = mt_rand(0, 9);
                $strUid .= $arDigits[$pos];
            }
        }

        // Returns, decorated according to mask
        return sprintf($mask, $strUid);
    }
    
    /**
     * Returns true if object is selected (by user session)
     *
     * @return boolean
     */
    public function isInWatchlist()
    {
        // Get IDs of items to compare
        $arMyListIds = sfContext::getInstance()->getUser()->getAttribute('arMyList', array());
        
        //debugvar($arMyListIds, 'Selected items:');
        return !empty($arMyListIds[$this->id]);
    }
    
    public function getCategoryName()
    {
        $name = '';
        if( $this->category_id > 0 )
        {
            $category = Category::getOrCreate($this->category_id);
            $name = $category->getName();
        }
        
        return $name;
    }
    
	protected $m_photoName = "";
	
	public function hasPhoto()
	{
		// No photo, we checked it
		if( $this->m_photoName == "-" )
		{
			return false;
		}
		
		// Check for photo
		if( $this->m_photoName == "" )
		{
			// Select from DB
			$this->m_photoName = "";
			
			$c = new Criteria();
			$c->add( FilesPeer::OBJ_ID, $this->id);
			$c->add( FilesPeer::OBJ_TYPE, MyConstants::TYPE_PRODUCT );
			$photo = FilesPeer::doSelectOne($c);
			if( $photo )
			{
				$this->m_photoName = $photo->getUname();
			}else 
			{
			    $this->m_photoName = "-";
			}
		}
		
		return $this->m_photoName != "-";
	}
	
	public function getPhotoName()
	{
		if( $this->hasPhoto() )
		{
			return $this->m_photoName;
		}
		
		return "";
	}
	
	
	/**
	 * Faq::hydrate()
	 * Sets culture to result set retrieved from database in order not to set it everytime when writing new method
	 * @param ResultSet $rs
	 * @param integer $startcol
	 *
	 */
	public function hydrate(ResultSet $rs, $startcol = 1)
	{
		$this->setCulture(sfContext::getInstance()->getUser()->getCulture());
		parent::hydrate($rs, $startcol);
	}

    public function getStatusName()
    {
        return MyConstants::getStatusName($this->status_id);
    }
    
    public function getPriceFmt()
    {
        return number_format($this->price / 100, 2);
    }
	public function getPromoPriceFmt()
    {
        return number_format($this->price_promo / 100, 2);
    }
	  
//    public function getPrice()
//    {
//        //debugvar($this->price, 'price product');
//        return $this->price/100;
//    }
//      
//    public function getPricePromo()
//    {
//        //debugvar($this->price_promo, 'price_promo product');
//        return $this->price_promo/100;
//    }
      
    /**
     * return branch categories by product id
     *
     * @param integer $id
     * @return unknown
     */
    public static function getBranch($id)
    {
    	//debugvar($id,'id');
		$product = ProductPeer::retrieveByPk($id);
		//debugvar($product,'product');
		$category = CategoryPeer::retrieveByPk($product->getCategoryId());
		//debugvar($category,'category');

		return $category->getBranch();
    }

    /**
     * Adds tag to field `tags` if tag is not assigned
     *
     * @param integer $tagId tag ID from MyConstants::USER_TAG_NNN
     */
    public function addTag($tagId)
    {
        // Add tag only if user has not such tag
        if( !$this->hasTag($tagId) )
        {
            // Ensure that each tag is separated whit colon
            $len = strlen($this->tags);
            if( $len == 0 )
            {
                $this->setTags($tagId . ':');
            }elseif( $this->tags[$len - 1] == ':' )
            {
                $this->setTags($this->getTags() . $tagId . ':');
            }else 
            {
                $this->setTags($this->getTags() . ':' . $tagId . ':');
            }
            
        }  // END IF ( need to assign tag )
    }
    
    /**
     * Removes tag from user
     *
     * @param integer $tagId tag ID from MyConstants::USER_TAG_NNN
     */
    public function removeTag($tagId)
    {
        $arTags = explode(':', $this->tags);
        $total = count($arTags);
//        debugvar($arTags);
        for( $i = 0; $i < $total; $i++ )
        {
            if( $arTags[$i] == $tagId )
            {
                // Unset tag and exit
                unset($arTags[$i]);
                $i = 1000;
            }
        }
        $this->setTags(join(':', $arTags));
        //debugvar('Set tag: ' . $this->getTags());
    }
    
    /**
     * Returns whether user is marked with tag from MyConstants::USER_TAG_NNN
     *
     * @param integer $tagId ID of tag to check
     * @return boolean
     */
    public function hasTag($tagId)
    {
        if( preg_match("/\\b" . (int)$tagId . "\\b/", $this->tags) )
        {
            return true;
        }
        
        return false;
    }

    /**
     * return array with records by tag
     *
     * @param string $tagId
     * @return object
     */
    public static function getByTag($tagId)
    {
        
        $c = new Criteria();
        $c->add(ProductPeer::STATUS_ID, MyConstants::STATUS_DELETED, Criteria::NOT_EQUAL);
        $c->add(ProductPeer::TAGS, ProductPeer::TAGS . ' REGEXP "[[:<:]]' . $tagId . '[[:>:]]"', Criteria::CUSTOM);
        return ProductPeer::doSelectWithI18n($c);
        
    }

}
